<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/3/22
 * Time: 14:28
 */

namespace App\Services;


use Illuminate\Support\Facades\Redis;

class MusicService
{

    /*
     * 音乐重新排序  锁定标识+应用量
     * */
    public function music_sort($category_arr)
    {
        if(!is_array($category_arr))
            return false;
        foreach ($category_arr as $value)
            $this->music_sort_rule($value);
        return true;
    }

    /*
     * 排序规则
     * 通过每个类型排序
     * 排序规则：1.取出未锁定排序位置的列表  2.重组数组 3.取出锁定排序的列表，遍历，通过排序指定插入到重组数组中
     * */
    private function music_sort_rule($category)
    {
        $category_redis_key = config('feild.redis.music_sort.key').$category;
        $category_max_lock_time = config('feild.redis.music_sort.lock_time');
        Redis::setex($category_redis_key, $category_max_lock_time, 1);

        // 重组数组
        $arr = [];
        // 通过应用排序取出
        $list = \App\Models\Music::select(['id', 'sort', 'number'])->where([['category', '=', $category], ['status', '=', '0'], ['is_delete', '=', '0'], ['flag', '!=', 1]])->orderby('number', 'desc')->orderby('sort', 'asc')->get();
        foreach ($list as $v)
            $arr[] = ['id'=>$v->id, 'sort'=>$v->sort, 'number'=>$v->number];

        // 取出固定排序音乐 flag = 1 是锁定的排序，插入锁定位置
        $flag_list = \App\Models\Music::select(['id', 'sort'])->where([['category', '=', $category], ['status', '=', '0'], ['is_delete', '=', '0'], ['flag', '=', 1]])->orderby('sort', 'asc')->get();
        foreach ($flag_list as $value){
            $sort = ($value->sort-1);
            array_splice($arr, $sort, 0, [['id'=>$value->id, 'sort'=>$value->sort]]); // 插入到位置3且删除0个
        }

        $i = 0;
        foreach ($arr as $update_value){
            $i++;
            \App\Models\Music::where([['id', '=', $update_value['id']]])->update(['sort'=>$i]);
        }
        Redis::del($category_redis_key);
        return true;
    }
    
}